package com.zsf.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsf.pojo.User;
import com.zsf.service.UserService;
import com.zsf.serviceImp.UserServiceImp;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService userService=new UserServiceImp();
	
		


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int count=0;
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter pw=response.getWriter();
		User userForA=new User();
		userForA.setAccount(request.getParameter("account"));
		count=count+userService.getUserExitst(userForA);
		if(count!=0){
			pw.print("<script>alert('该账号已注册过，注册失败，按确定键返回注册界面')</script>");
			response.sendRedirect("register.jsp");
		}else{
			User userForE=new User();
			userForE.setEmail(request.getParameter("E-mail"));
			count=count+userService.getUserExitst(userForE);
			if(count!=0){
				pw.print("<script>alert('该邮箱已注册过，注册失败，按确定键返回注册界面')</script>");
				response.sendRedirect("register.jsp");
			}else{
				User userForP=new User();
				userForP.setPhoneNum(request.getParameter("phoneNum"));
				count=count+userService.getUserExitst(userForP);
				if(count!=0){
					pw.print("<script>alert('该手机号已注册过，按确定键返回注册界面')</script>");
					response.sendRedirect("register.jsp");
				}else{
					User userForN=new User();
					userForN.setUserName(request.getParameter("userName"));
					count=count+userService.getUserExitst(userForN);
					if(count!=0){
						pw.print("<script>alert('该用户名已注册过，按确定键返回注册界面')</script>");
						response.sendRedirect("register.jsp");
					}else{
						if(count==0){
							User user=new User();
							user.setAccount(request.getParameter("account"));
							user.setEmail(request.getParameter("E-mail"));
							user.setPassword(request.getParameter("password"));
							user.setPhoneNum(request.getParameter("phoneNum"));
							user.setUserName(request.getParameter("userName"));
							if(!user.getAccount().equals("")){
								userService.insertUser(user);
								pw.print("<script language='JavaScript' type='text/javascript'>alert('注册成功，点击确定跳转到登录页面'); window.location.href='login.jsp';</script>");
							}else{
								pw.print("<script language='JavaScript' type='text/javascript'>alert('请先输入注册信息，按确定键返回注册界面');window.location.href='register.jsp';</script>");
							}
						}
					}
				}
			}
		}
	}

}
